import { resolve } from 'path'
import { defineConfig } from 'vite'

import fs from 'node:fs';
import path from 'node:path';

const copy = function(opts){
	return {
		name : 'vite-plugin-copies',
		apply: 'build',
		closeBundle(){
			let exists = (file) => {
				try {
					fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK);
					return true;
				}
				catch (err) {
					return false;
				}
			}
			let copy = (src, tar) => {
				if( Array.isArray(src) ){
					return src.forEach(s => copy(s, tar));
				}
				if( Array.isArray(tar) ){
					return tar.forEach(t => copy(src, t));
				}
				if( typeof(src) != 'string' ){
					throw new Error('illegal src argument.' + src);
				}
				if( typeof(tar) != 'string' ){
					throw new Error('illegal tar argument.' + tar);
				}

				if( !exists(src) ){
					throw new Error("can't found src." + src);
				}

				let target = path.extname(tar) ? tar :  path.resolve(tar, path.basename(src));
				let dir = path.dirname(target);
				if( !exists(dir) ){
					fs.mkdirSync(dir);
				}

				let stat = fs.statSync(src);
				if( stat.isFile() ){
					fs.copyFileSync(src, target);
				}
				else if( stat.isDirectory() ){
					fs.readdirSync(src).forEach(name => {
						copy(path.resolve(src, name), target);
					});
				}
				else {
					throw new Error('unsupport src.' + src);
				}
			}
			(opts.targets || []).forEach(item => {
				copy(item.src, item.dest);
			});
		}
	}
}

export default defineConfig(({ command, mode, ssrBuild }) => {
	if( command == 'build' ){
		let opts = {
			build : {
				minify: 'esbuild',
			},
			esbuild: {
				drop: ['console', 'debugger']
			},
		}
		if( mode == 'demo' ){
			Object.assign(opts, {
				base: './',
				plugins: [
					copy({
						targets: [
							{ src: 'assets', dest: 'dist/demo' },
						]
					})
				],
			});
			Object.assign(opts.build, {
				outDir : 'dist/demo',
				rollupOptions: {
					input: {
						main: resolve(__dirname, 'index.html'),
					},
				}
			});
			return opts;
		}
		else {
			Object.assign(opts.build, {
				lib: {
					entry: resolve(__dirname, 'index.js'),
					name: 'Markup',
					fileName: 'markup'
				},
			});
			return opts;
		}
	}
	return {};
});